<?php


namespace app\api\service;


class DouAccessToken
{
    private $tokenUrl;
    const TOKEN_CACHED_KEY = 'access';
    const TOKEN_EXPIRE_IN = 7000;

    function __construct()
    {
        $url = config('dou.access_token_url');
        $url = sprintf($url, config('dou.app_id'), config('dou.app_secret'));
        $this->tokenUrl = $url;
    }

    public function get()
    {
        $token = $this->getFromCache();

        if(!$token){
            return $this->getFromDouServer();
        }else{
            return $token;
        }
    }

    private function getFromCache()
    {
        $token = cache(self::TOKEN_CACHED_KEY);

        if(!$token){
            return $token;
        }

        return null;
    }

    private function getFromDouServer()
    {
        $token = curl_get($this->tokenUrl);
        $token = json_decode($token, true);

        if(!$token){
            throw new \Exception('获取AccessToken失败');
        }

        if($token['err_no'] != 0){
            throw new \Exception($token['err_no']);
        }
        $this->saveTocache($token);

        return $token;
    }

    private function saveToCache($token){
        cache(self::TOKEN_CACHED_KEY, $token, $token["data"]["expires_in"]);
    }
}